package com.swak.frame.util;

import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.swak.frame.exception.JacksonException;

public class JacksonUtils {
    private static final ObjectMapper mapper = new ObjectMapper();

    static {
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 主要是这句处理
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    public static <T> T parseObject(String json, Class<T> clazz) {
        try {
            return mapper.readValue(json, clazz);
        } catch (Exception e) {
            throw new JacksonException(e);
        }
    }

    public static JsonNode parseObject(String text) {
        try {
            return mapper.readTree(text);
        } catch (Exception e) {
            throw new JacksonException(e);
        }
    }

    public static Map<String, String> toMapString(JsonNode jsonNode) {
        try {
            return mapper.convertValue(jsonNode, new TypeReference<Map<String, String>>() {/**/});
        } catch (Exception e) {
            throw new JacksonException(e);
        }
    }

    public static <T> List<T> parseArray(String text, Class<T> clazz) {
        try {
            return mapper.readValue(text, new TypeReference<List<T>>() {/**/});
        } catch (Exception e) {
            throw new JacksonException(e);
        }
    }

    public static String toJSONString(Object object) {
        try {
            return mapper.writeValueAsString(object);

        } catch (Exception e) {
            throw new JacksonException(e);
        }
    }

    public static byte[] writeValueAsBytes(Object object) {
        try {
            return mapper.writeValueAsBytes(object);
        } catch (Exception e) {
            throw new JacksonException(e);
        }
    }
}
